/*
 * @Author: 橘子
 * @Date: 2023/7/9
 * @Project_description: 删除线上文件列表
 * @Description: 代码是我抄的，不会也是真的
 */
'use strict'

const qiniu = require("qiniu");
const config = require('./config.cicd')

// 生成上传凭证
const mac = new qiniu.auth.digest.Mac(config.accessKey, config.secretKey);
let configQiniu = new qiniu.conf.Config();
configQiniu.zone = config.zone; // 空间对应的机房
const bucketManager = new qiniu.rs.BucketManager(mac, config);


/**
 * @Description: 删除文件
 * @author 橘子
 */
const deleteFileList = (list) => {
    return new Promise((resolve, reject) => {
        bucketManager.batch(list, function (err, respBody, respInfo) {
            if (err) {
                console.log("文件删除失败!", err)
                resolve(false);
            }
            if (respInfo.statusCode === 200) {
                resolve(true);
            } else {
                console.log("文件删除失败!", respBody, respInfo);
                resolve(false);
            }
        });
    })
}


const getDir = (options) => {
    return new Promise((resolve, reject) => {
        bucketManager.listPrefix(config.scope, options, function (err, respBody, respInfo) {
            if (err) {
                console.log('获取文件失败', err);
                resolve(false)
            }
            if (respInfo.statusCode === 200) {
                //如果这个nextMarker不为空，那么还有未列举完毕的文件列表，下次调用listPrefix的时候，
                //指定options里面的marker为这个值
                let nextMarker = respBody.marker;
                let items = respBody.items;
                resolve({
                    nextMarker,
                    items
                })
            } else {
                console.log('获取文件失败', respInfo, respBody)
                resolve(false)
            }
        });
    })
}


const install = async () => {
    let options = {
        limit: 99999,
        prefix: config.scopePath,
    }
    //递归获取文件列表
    let list = await getDir(options)
    if (list) {
        console.log('文件数:', list.items.length)
        //处理文件列表
        let fileList = list.items.map(item => {
            return qiniu.rs.deleteOp(config.scope, item.key);
        })
        if (fileList.length !== 0) {
            //批量删除
            let result = await deleteFileList(fileList)
            if (result) {
                console.log('文件删除成功')
            }
        }
    }

}
module.exports = {
    deleteFileList,
    install
}
